﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM.Parts
{
    public partial class OutgoingPayment : System.Web.UI.Page
    {
        #region Fields

        private string TblHeaderName = "OVPM";
        private string TblLineName = "VPM2";
        private string CurrentPageUrl = "/Business/Parts/Purchasing/OutgoingPayment.aspx";
        private string HeaderKeyName = "DocEntry";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../../Login.aspx");
                }

                if (!IsPostBack)
                {
                    ClearScreen();

                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());

                    String outPmtId = Request.QueryString["outPmt_id"];
                    if (!String.IsNullOrEmpty(outPmtId))
                    {
                        LoadData(outPmtId, ConvertDocType.Get2String(DocType.OUTGOING));
                        SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }

                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvIncPmt.PageIndex = e.NewPageIndex;
            DataTable tblVPM2 = (DataTable)Session["OutPmtTable"];
            BindData(tblVPM2);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["OutPmtTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvIncPmt.EditIndex = -1;
                    BindData((DataTable)Session["OutPmtTable"]);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        private void DisableControl()
        {
            this.btnSave.Visible = false;
            this.txtRemarks.Enabled = false;
            this.btnCancel.Visible = false;
            this.grvIncPmt.Columns[0].Visible = false;
            for (int i = 0; i < this.grvIncPmt.Rows.Count; i++)
            {
                TextBox txtOrderQuantity = (TextBox)this.grvIncPmt.Rows[i].FindControl("txtOrderQuantity");
                txtOrderQuantity.Enabled = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        private DataRow FillShipToAddress(string outletId, bool isFill)
        {
            try
            {
                if (outletId.Length > 0)
                {
                    MasterData obj = new MasterData();
                    DataSet tbWareHouse = null;
                    if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
                    {
                        DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
                        if (r.Length > 0)
                        {
                            if (isFill)
                            {
                                StringBuilder shipTo = new StringBuilder();
                                shipTo.AppendLine(r[0]["Block"].ToString());
                                shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
                                shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
                            }
                            else return r[0];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvIncPmt.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["OutPmtTable"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvIncPmt.EditIndex = -1;
            BindData((DataTable)Session["OutPmtTable"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvIncPmt.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["OutPmtTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvIncPmt.EditIndex = -1;
                    BindData((DataTable)Session["OutPmtTable"]);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["OutPmtTable"] = tblData;
            this.grvIncPmt.DataSource = tblData;
            this.grvIncPmt.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = DateTime.Now;
                    if (Utils.AppConstants.isDateTime(this.txtPostingDate.Text))
                    {
                        poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    }
                    DataTable tblIncPmt = (DataTable)Session["OutPmtTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtVendorCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtVendorName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            this.txtCntctName.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;

                            Transaction trx = new Transaction();
                            DataTable dtContents = trx.GetDocumentForPayment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), txtVendorCode.Text, poDate).Tables[0];
                            dtContents = BuildContents(dtContents);

                            BindData(dtContents);
                            updateTableTotalPrice();

                            if (tblIncPmt != null) tblIncPmt.Rows.Clear();
                            Session["ChosenBP"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string incPmtId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            LoadData(incPmtId, ConvertDocType.Get2String(DocType.OUTGOING));
                            break;

                        case "SelectAccount":
                            GridViewRow rowAccount = Session["ChosenAccount"] != null ? (GridViewRow)Session["ChosenAccount"] : null;
                            txtAccountCode.Text = ((Label)rowAccount.FindControl("lblAccountCode")).Text;
                            txtAccountName.Text = ((Label)rowAccount.FindControl("lblAcctName")).Text;
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        public String _collectData()
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("Series"); // 
                dtHeader.Columns.Add("DocType");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("PayNoDoc");
                dtHeader.Columns.Add("NoDocSum");
                dtHeader.Columns.Add("Address");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");

                if (ddlPaymentMeans.SelectedValue.Equals("C")) // Cash
                {
                    dtHeader.Columns.Add("CashAcct");
                    dtHeader.Columns.Add("CashSum");
                }
                else if (ddlPaymentMeans.SelectedValue.Equals("B")) // Bank Transfer
                {
                    dtHeader.Columns.Add("TrsfrAcct");
                    dtHeader.Columns.Add("TrsfrSum");
                }

                CultureInfo ivC = new System.Globalization.CultureInfo("es-US");
                DataRow drHeader = dtHeader.NewRow();

                drHeader["Series"] = 18;
                drHeader["DocType"] = "S";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["CardCode"] = txtVendorCode.Text;
                drHeader["CardName"] = txtVendorName.Text.Trim();
                drHeader["Address"] = txtBillTo.Text;

                if (ddlPaymentMeans.SelectedValue.Equals("C")) // Cash
                {
                    drHeader["CashAcct"] = txtAccountCode.Text;
                    drHeader["CashSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(lblTotalAmountDue.Text), "SumDec");
                }
                else if (ddlPaymentMeans.SelectedValue.Equals("B")) // Bank Transfer
                {
                    drHeader["TrsfrAcct"] = txtAccountCode.Text;
                    drHeader["TrsfrSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(lblTotalAmountDue.Text), "SumDec");
                }

                if (chkPmtOnAccount.Checked)
                {
                    drHeader["PayNoDoc"] = "Y";
                    drHeader["NoDocSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentAccount.Text), "SumDec");
                }
                else
                {
                    drHeader["PayNoDoc"] = "N";
                    drHeader["NoDocSum"] = 0;
                }
                // UDF
                drHeader["U_ContactPerson"] = txtCntctName.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;
                dtHeader.Rows.Add(drHeader);

                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("InvType");
                dt.Columns.Add("SumApplied");
                dt.Columns.Add("vatApplied");
                dt.Columns.Add("DocLine");
                //dt.Columns.Add("baseAbs");

                foreach (GridViewRow rowView in this.grvIncPmt.Rows)
                {
                    if (((CheckBox)rowView.FindControl("chkSelected")).Checked)
                    {
                        DataRow drContents = dt.NewRow();
                        drContents["DocEntry"] = ((Label)rowView.FindControl("lblDocument")).Text;
                        drContents["InvType"] = ((Label)rowView.FindControl("lblDocType")).Text;
                        drContents["SumApplied"] = GF.ResetFormatNumeric(((TextBox)rowView.FindControl("txtTotalPaymets")).Text);
                        drContents["DocLine"] = ((Label)rowView.FindControl("lblDocLine")).Text;
                        dt.Rows.Add(drContents);
                    }
                }


                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                dt.TableName = TblLineName;
                ds.Tables.Add(dtHeader.Copy());
                ds.Tables.Add(GF.ResetFormatNumeric(dt, new string[] { "SumApplied" }).Copy());

                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.OUTGOING), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtVendorCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Business Partner','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtVendorCode.Focus();
                    return;
                }

                if ((chkPmtOnAccount.Checked) & (string.IsNullOrEmpty(txtPaymentAccount.Text) || double.Parse(txtPaymentAccount.Text) <= 0))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Confirmation Amount must be greater than zero','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtPaymentAccount.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtAccountCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Payment Account is not defined','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtAccountCode.Focus();
                    return;
                }

                String requestXML = _collectData();
                if (requestXML == "") return;

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                Transaction ts = new Transaction();

                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.OUTGOING), "", false, dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction obj = new Transaction();
                string error = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("DocNum");
            dt.Columns.Add("InvType");
            dt.Columns.Add("RefDate");
            dt.Columns.Add("DueDate");
            dt.Columns.Add("Overdue");
            dt.Columns.Add("BalDueDeb");
            dt.Columns.Add("SumApplied");
            dt.Columns.Add("DocLine");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();

                    row["No"] = dr["No"];
                    row["DocNum"] = dr["DocNum"];
                    row["InvType"] = dr["InvType"];
                    row["RefDate"] = DateTime.Parse(dr["RefDate"].ToString(), new CultureInfo("es-US")).ToString("dd/MM/yyyy");
                    row["DueDate"] = DateTime.Parse(dr["DueDate"].ToString(), new CultureInfo("es-US")).ToString("dd/MM/yyyy");
                    row["Overdue"] = dr["Overdue"];
                    row["BalDueDeb"] = GF.FormatNumeric(dr["BalDueDeb"].ToString().Equals("") ? "0" : dr["BalDueDeb"].ToString(), "SumDec");
                    row["SumApplied"] = GF.FormatNumeric(dr["SumApplied"].ToString().Equals("") ? "0" : dr["SumApplied"].ToString(), "SumDec");
                    row["DocLine"] = dr["DocLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadData(String incPmtId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, incPmtId, dbType);
            DataTable dtHeader = null;

            if (returnDoc == null)
            {
                incPmtId = "1";
                returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, incPmtId, dbType);
                if (returnDoc != null || returnDoc.Tables.Count >= 2) dtHeader = returnDoc.Tables[0];
            }
            else
                if (returnDoc.Tables.Count > 0)
                {
                    dtHeader = returnDoc.Tables[0];
                }

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }


            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            if (dtHeader.Rows.Count > 0)
            {
                DataRow dr = dtHeader.Rows[0];

                this.txtOutNo.Text = dr["DocEntry"].ToString();
                this.txtVendorCode.Text = dr["CardCode"].ToString();
                this.txtVendorName.Text = dr["CardName"].ToString();
                this.txtCntctName.Text = dr["U_ContactPerson"].ToString();

                GetDefault getDefault = new GetDefault();

                if (!String.IsNullOrEmpty(dr["CashAcct"].ToString())) // Cash
                {
                    ddlPaymentMeans.SelectedValue = "C";
                    txtAccountCode.Text = dr["CashAcct"].ToString();
                    txtAccountName.Text = getDefault.GetAccountNameByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["CashAcct"].ToString());
                }
                else // Bank Transfer
                {
                    ddlPaymentMeans.SelectedValue = "B";
                    txtAccountCode.Text = dr["TrsfrAcct"].ToString();
                    txtAccountName.Text = getDefault.GetAccountNameByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["TrsfrAcct"].ToString());
                }

                txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
                txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
                txtDueDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], new CultureInfo("es-US")));

                txtRemarks.Text = dr["Comments"].ToString();

                if (NewDocType != ConvertDocType.Get2String(DocType.OUTGOING))
                    SetScreenStatus("New");
                else SetScreenStatus("Update");

                BindData(dtContents);
                updateTableTotalPriceAllLine();
            }
        }

        protected void LoadDefault()
        {
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDueDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtOutNo.Text =
            this.txtCntctName.Text =
            this.txtBillTo.Text =
            this.txtVendorCode.Text =
            this.txtVendorName.Text =
            this.txtAccountCode.Text =
            this.txtAccountName.Text = string.Empty;
            this.ddlPaymentMeans.SelectedValue = "B";
            DataTable dtContents = BuildContents(null);
            BindData(dtContents);
        }

        protected void ClearScreen()
        {
            DataTable dtHeader = new DataTable(TblHeaderName);

            dtHeader.Columns.Add("Series");
            dtHeader.Columns.Add("DocDate");
            dtHeader.Columns.Add("DocDueDate");
            dtHeader.Columns.Add("TaxDate");
            dtHeader.Columns.Add("CardCode");
            dtHeader.Columns.Add("CardName");
            dtHeader.Columns.Add("CntctCode"); // contac person
            dtHeader.Columns.Add("Address");
            dtHeader.Columns.Add("Comments");
            dtHeader.Rows.Add();

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;

            txtPostingDate.Text.ToString(ci);
            txtDueDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtVendorCode.Text =
            txtVendorName.Text =
            txtRemarks.Text =
            txtCntctName.Text =
            txtAccountCode.Text =
            txtAccountName.Text = string.Empty;
            ddlPaymentMeans.SelectedIndex = 0;

            // Details
            DataTable dtContents = new DataTable(TblLineName);
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("DocNum");
            dtContents.Columns.Add("InvType");
            dtContents.Columns.Add("RefDate");
            dtContents.Columns.Add("DueDate");
            dtContents.Columns.Add("Overdue");
            dtContents.Columns.Add("BalDueDeb");
            dtContents.Columns.Add("SumApplied");
            dtContents.Columns.Add("DocLine");

            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnSave.Visible = true;
                    btnCancel.Visible = true;
                    hdnIsUpdate.Value = "false";
                    ddlPaymentMeans.SelectedValue = "B";
                    txtAccountCode.Text =
                    txtAccountName.Text = String.Empty;
                    btnGLAccount.Visible = true;
                    break;

                case "Update":
                    btnSave.Visible = true;
                    btnCancel.Visible = true;
                    hdnIsUpdate.Value = "false";
                    btnGLAccount.Visible = false;
                    break;

                case "Close":
                    btnSave.Visible = false;
                    btnCancel.Visible = true;
                    btnGLAccount.Visible = false;
                    break;
            }
        }

        protected void updateTableTotalPrice()
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            double orderTotal = 0.0;
            foreach (GridViewRow rowView in this.grvIncPmt.Rows)
            {
                if (((CheckBox)rowView.FindControl("chkSelected")).Checked)
                {
                    double total = 0.0;
                    if (rowView.FindControl("txtTotalPaymets") != null)
                        total = GF.Object2Double((object)GF.ResetFormatNumeric(((TextBox)rowView.FindControl("txtTotalPaymets")).Text), "SumDec");
                    orderTotal += total;
                }
            }
            orderTotal += GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentAccount.Text), "SumDec");
            lblTotalAmountDue.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
            lblOpenBalance.Text = txtPaymentAccount.Text = GF.FormatNumeric(txtPaymentAccount.Text, "SumDec");
        }

        protected void updateTableTotalPriceAllLine()
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            double orderTotal = 0.0;
            foreach (GridViewRow rowView in this.grvIncPmt.Rows)
            {
                double total = 0.0;
                if (rowView.FindControl("txtTotalPaymets") != null)
                    total = GF.Object2Double((object)GF.ResetFormatNumeric(((TextBox)rowView.FindControl("txtTotalPaymets")).Text), "SumDec");
                orderTotal += total;
            }
            orderTotal += GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentAccount.Text), "SumDec");
            lblTotalAmountDue.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
            lblOpenBalance.Text = txtPaymentAccount.Text = GF.FormatNumeric(txtPaymentAccount.Text, "SumDec");
        }

        protected void chkPmtOnAccount_CheckedChanged(object sender, EventArgs e)
        {
            txtPaymentAccount.Text = "0.00";
            txtPaymentAccount.Visible = ((CheckBox)sender).Checked;
            updateTableTotalPrice();
        }

        protected void chkSelected_CheckedChanged(object sender, EventArgs e)
        {
            updateTableTotalPrice();
        }

        protected void txtPaymentAccount_TextChanged(object sender, EventArgs e)
        {
            updateTableTotalPrice();
        }

        protected void ddlPaymentMeans_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((DropDownList)sender).SelectedValue.Equals("C"))
            {
                btnGLAccount.Visible = false;
                txtAccountCode.Text = "1111-00";
                txtAccountName.Text = "Cash on hand - VND (Tiền VND)";
            }
            else
            {
                btnGLAccount.Visible = true;
                txtAccountCode.Text =
                txtAccountName.Text = string.Empty;
            }

        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsOutNo = fGetDefault.GetMaxDocEntry
            (
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.OUTGOING),
                TblHeaderName, HeaderKeyName
            );
            if (txtOutNo.Text.CompareTo(lsOutNo) != 0) Response.Redirect(CurrentPageUrl + "?outPmt_id=" + lsOutNo);
        }
    }
}